﻿using System;
using System.Collections.Generic;
using System.Linq;
using Yyyg.IBLL;
using Yyyg.Models;

namespace Yyyg.BLL
{
    public class OrdersService : TableServiceBase<Orders>, IOrdersService
    {
        //订单添加同步锁
        static readonly object order_lock = new object();

        LuckyEntities db;

        public OrdersService(LuckyEntities db) : base(db)
        {
            this.db = db;
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="items"></param>
        /// <param name="uid"></param>
        /// <param name="addrid">收获地址id,为负数则设定为默认地址</param>
        public void CommitOrder(IList<OrderItem> items, int uid, int addrid = -1)
        {
            //不允许相同的夺宝id出现在一批订单
            if (items.Any(t => items.Count(c => c.RushID == t.RushID) > 1)) throw new ApplicationException("订单包含重复项");

            var now = DateTime.Now;
            int sum = items.Sum(s => s.ByCount);
            var user = db.Member.First(f => f.Uid == uid);
            if (db.ReceInfo.Count(c => c.Uid == uid) == 0) throw new ApplicationException("没有可用的收货地址");
            if (user.Acbal < sum) throw new ApplicationException("账户余额不足");
            if (addrid < 0) addrid = db.ReceInfo.First(f => f.Uid == uid).Id;
            lock (order_lock)
            {
                //获取所有相关夺宝项
                var que = db.Rushby_all.In("Id", items.Select(s => s.RushID));

                var negative = que.FirstOrDefault(a => a.Rem < items.First(f => f.RushID == a.Id).ByCount);
                if (negative != null) throw new ApplicationException("商品\"" + negative.Goods.Title + "\"剩余人次不足");
                foreach (var s in items)
                {
                    //添加订单
                    db.Orders.Add(new Orders()
                    {
                        Uid = uid,
                        Bycount = s.ByCount,
                        Rush_id = s.RushID,
                        Createtime = now,
                        Payment = s.ByCount,
                        Status = 0,
                        Receid = addrid
                    });
                }
                user.Acbal -= sum;
                db.SaveChanges();

                //其他逻辑(夺宝详情记录添加,剩余人数减少等)在触发器中
                CheckRushOver();
            }
        }

        //检测是否满足开奖条件,如果是则进行开奖
        private void CheckRushOver()
        {
            var res = db.Rushby_all.Where(w => w.Rem <= 0 && w.Status == 0);
            if (res.Count() == 0) return;
            //获取参与计算的"老时时彩"开奖号码
            int ticknum = new Random().Next(10000, 100000);
            db.AnnounceWinner(ticknum);

            //计算开奖号码
            //DateTime now = DateTime.Now;
            /*
            //第一:id= 133 : time=
            //第二:
            //获取参与计算的小于当前时间的最后50条订单记录
            var ors = db.Orders.OrderByDescending(o => o.Createtime).Take(50).ToArray();
            //计算总和
            int sum = ors.Sum(or => Convert.ToInt32(or.Createtime.ToString("HHmmss")));
            foreach (var rush in res)
            {
                
                //计算最终开奖号码
                int lotnum = 10000001 + ((sum + ticknum) % rush.All_told);
                //获取中奖的用户
                var winuser = db.Rushby_det.First(f => f.RobNumStart <= lotnum && f.RobNumEnd >= lotnum);
                var rsover = new Rushby_over();
                rsover.BeenViewed = false;
                rsover.Createtime = now;
                rsover.Bycount = db.Orders.Where(w => w.Uid == winuser.Uid && w.Rush_id == rush.Id).Sum(s => s.Bycount);
                rsover.Rush_id = rush.Id;
                rsover.Uid = winuser.Uid;
                rsover.Sum50 = sum;
                rsover.TotalNum = rush.All_told;
                rsover.Lott_num = lotnum;
                rsover.TicketNum = ticknum;
                //将其添加到开奖列表
                db.Rushby_over.Add(rsover);
                //其他逻辑在Rushby_over触发器中
            }
            db.SaveChanges();
            */
        }
    }
}
